package com.ruoyi.web.controller.sincerity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Size;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SinQuery;
import com.ruoyi.system.service.ISinQueryService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 疑问管理Controller
 *
 * @author buke
 * @date 2023-03-10
 */
@RestController
@RequestMapping("/system/query")
public class SinQueryController extends BaseController
{
    public static final String STUDENT = "学生" ;
    public static final String TEACHER = "教师" ;
    @Autowired
    private ISinQueryService sinQueryService;
    @Autowired
    private ISysUserService userService ;
    @Autowired
    private ISysDeptService deptService ;
    /**
     * 查询疑问管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SinQuery sinQuery)
    {
        /**pageHelp自动分页  逻辑分页*/
        startPage();
        /**设置用户权限  获取当前登录用户的 所有角色id */
        List<SysRole> roles = SecurityUtils.getLoginUser().getUser().getRoles();
        List<SysUser> users = new ArrayList<>() ;
        for (SysRole role : roles) {
            if (StringUtils.isNotBlank(role.getRoleName())) {
                /**如果是学生  则设置发起人id ,查询时会添加这个条件*/
                if (STUDENT.equals(role.getRoleName())){
                    sinQuery.setStartId(SecurityUtils.getUserId());
//                    SysUser user = new SysUser();
//                    user.setDeptId(SecurityUtils.getDeptId());
//                    users.addAll(userService.selectUserList(user));
                    break;
                }else {
                    /**如果不是管理员*/
                    if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())){
                        SysUser user = SecurityUtils.getLoginUser().getUser();
                        SysUser sysUser = new SysUser();
                        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
                        wrapper.eq(SysDept::getLeader,user.getNickName()) ;
                        List<SysDept> list = this.deptService.list(wrapper);
                        if (CollectionUtils.isNotEmpty(list)){
                            for (SysDept sysDept : list) {
                                sysUser.setDeptId(sysDept.getDeptId());
                                users.addAll(userService.selectUserList(sysUser)) ;
                            }
                        }
                    }
                    if (CollectionUtils.isNotEmpty(users)){
                        users = users.stream().distinct().collect(Collectors.toList()) ;
                    }
                    break;
                }
            }
        }
        /**使用Mybatis plus 语法查询数据*/
        LambdaQueryWrapper<SinQuery> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(sinQuery.getCreateBy()),SinQuery::getCreateBy,sinQuery.getCreateBy()) ;
        wrapper.like(StringUtils.isNotBlank(sinQuery.getAnswerName()),SinQuery::getAnswerName,sinQuery.getAnswerName()) ;
        wrapper.eq(!Objects.isNull(sinQuery.getStartId()),SinQuery::getStartId,sinQuery.getStartId()) ;
        wrapper.eq(!Objects.isNull(sinQuery.getState()),SinQuery::getState,sinQuery.getState()) ;
        /**老师的学生  数组不为空则添加筛选条件*/
        if (CollectionUtils.isNotEmpty(users)){
            List<String> collect = new ArrayList<>(users.stream().collect(Collectors.toMap(SysUser::getNickName, SysUser::getUserId)).keySet());
            wrapper.in(SinQuery::getStartName,collect);
        }
        List<SinQuery> list = sinQueryService.list(wrapper);


        for (SinQuery query : list) {
            if (!Objects.isNull(query.getState())) {
                query.setStateDescribe(query.getState() == 0L ? "否" : "是");
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出疑问管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:query:export')")
    @Log(title = "疑问管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SinQuery sinQuery)
    {
        List<SinQuery> list = sinQueryService.selectSinQueryList(sinQuery);
        ExcelUtil<SinQuery> util = new ExcelUtil<SinQuery>(SinQuery.class);
        util.exportExcel(response, list, "疑问管理数据");
    }

    /**
     * 获取疑问管理详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sinQueryService.selectSinQueryById(id));
    }

    /**
     * 新增疑问管理
     */
    @Log(title = "疑问管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SinQuery sinQuery)
    {
        return toAjax(sinQueryService.insertSinQuery(sinQuery));
    }

    /**
     * 修改疑问管理
     */
    @Log(title = "疑问管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SinQuery sinQuery)
    {
        return toAjax(sinQueryService.updateSinQuery(sinQuery));
    }

    /**
     * 删除疑问管理
     */
    @Log(title = "疑问管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sinQueryService.deleteSinQueryByIds(ids));
    }

    /**
     * 答复疑问
     */
    @Log(title = "答复疑问", businessType = BusinessType.UPDATE)
    @PutMapping("/answerQuery")
    public AjaxResult answerQuery(@RequestBody SinQuery sinQuery)
    {
        sinQuery.setAnswerId(SecurityUtils.getUserId());
        sinQuery.setAnswerName(SecurityUtils.getLoginUser().getUser().getNickName());
        sinQuery.setState(1L);
        return toAjax(sinQueryService.updateSinQuery(sinQuery));
    }
}
